package com.opesoft.pf.page;

import java.lang.reflect.ParameterizedType;

import org.apache.log4j.Logger;

import com.opesoft.fw.ajax.Ajax;
import com.opesoft.fw.ajax.AjaxWebManager;
import com.opesoft.fw.core.exception.MessageException;
import com.opesoft.pf.jpa.SimpleBO;

public abstract class SimpleAction<T>
{
	protected Class<T> _T;
	@SuppressWarnings("unused")
	protected Class<SimpleBO<Object>> boClass;
	protected Class<QueryForm> formClass;
	protected String pageName;

	Logger log=Logger.getLogger(this.getClass());

	@SuppressWarnings("unchecked")
	public SimpleAction(Class boClass,Class formClass)
	{
		this.boClass=boClass;
		this.formClass=formClass;

		_T=(Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		log.debug("Create new SimpleAction<"+_T+">");

		this.pageName=_T.getSimpleName();
		if(this.pageName!=null&&this.pageName.length()>0)
		{
			this.pageName=this.pageName.substring(0,1).toLowerCase()+this.pageName.substring(1);
			log.debug("pageName : "+this.pageName);
		}
	}

	@Ajax(forward=true, clientCall=true)
	public String add()
	{
		AjaxWebManager.request().setAttribute("op","insert");
		return this.pageName+".edit.jsp";
	}

	@Ajax(forward=true)
	public String insert() throws Exception
	{
		T e=AjaxWebManager.populate(_T);
		this.boClass.newInstance().insert(e);
		return this.add();
	}

	@Ajax(clientCall=true)
	public void del(String[] ids) throws Exception
	{
		this.boClass.newInstance().del(ids);
	}

	@Ajax(forward=true, clientCall=true)
	public String edit(String id) throws Exception
	{
		T e=this.boClass.newInstance().find(id);
		if(e!=null)
		{
			AjaxWebManager.request().setAttribute("op","update");
			AjaxWebManager.request().setAttribute("data",e);
		}
		else return this.add();

		return this.pageName+".edit.jsp";
	}

	@SuppressWarnings("unchecked")
	@Ajax(forward=true, clientCall=true)
	public String update() throws Exception
	{
		SimpleBO<T> bo=(SimpleBO<T>)this.boClass.newInstance();
		T e=bo.find(AjaxWebManager.request().getParameter("id"));
		AjaxWebManager.populate(e);
		bo.update(e);
		return this.add();
	}

	@Ajax(clientCall=true)
	public AjaxQueryResult query() throws MessageException
	{
		QueryForm form=AjaxWebManager.populate(this.formClass);
		return form.query();
	}
}
